package com.zyk.scaffold.oauth.keypool.controller;


import com.alibaba.csp.sentinel.util.AssertUtil;
import com.zyk.scaffold.core.domain.Result;
import com.zyk.scaffold.oauth.keypool.auth.JwtKeyIdsHelper;
import com.zyk.scaffold.oauth.keypool.pojo.dto.KeyIdsContext;
import com.zyk.scaffold.oauth.keypool.pojo.dto.KeyInfoDTO;
import com.zyk.scaffold.oauth.keypool.pojo.responses.PullKeysResponse;
import com.zyk.scaffold.oauth.keypool.service.KeyPoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 秘钥池控制层
 */
@RestController
@RequestMapping("key-pool")
public class KeyPoolController {

    @Autowired
    private KeyPoolService keyPoolService;

    @GetMapping("/pull/keys")
    public Result<PullKeysResponse> pullKeys(@RequestParam("nums") int nums) {
        AssertUtil.isTrue(nums > 0, "nums 必须大于 0");
        PullKeysResponse pullKeysResponse = new PullKeysResponse();
        List<KeyInfoDTO> keyInfos = keyPoolService.getRandomKeys(nums);
        List<Integer> keyIds = new ArrayList<>();
        List<String> publicKeys = new ArrayList<>();
        for (KeyInfoDTO keyInfo : keyInfos) {
            keyIds.add(keyInfo.getId());
            publicKeys.add(keyInfo.getPublicKey());
        }
        String keyToken = JwtKeyIdsHelper.toJwt(KeyIdsContext.creatKeyIdsContext(keyIds));
        pullKeysResponse.setPublicKeys(publicKeys);
        pullKeysResponse.setKeyToken(keyToken);
        return Result.ok(pullKeysResponse);
    }
}
